package com.yipin.neimeng.service.impl;



import cn.hutool.http.Header;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yipin.neimeng.constant.ErrorConstant;

import com.yipin.neimeng.dbpojo.NeimengCmccMsg;
import com.yipin.neimeng.mapper.NeiMengCmccMsgMapper;
import com.yipin.neimeng.request.YunShuSendMessageCodeRequest;
import com.yipin.neimeng.service.NeiMengCmccMsgService;

import com.yipin.neimeng.util.HttpJsonInvokeDemo;
import com.yipin.neimeng.vo.ResultMsg;
import lombok.extern.slf4j.Slf4j;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Service;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

//import static com.yipin.neimeng.constant.HttpJsonInvokeDemo.decryptMessage;


@Service
@Slf4j
public class NeiMengCmccMsgServiceImpl extends ServiceImpl<NeiMengCmccMsgMapper, NeimengCmccMsg> implements NeiMengCmccMsgService {
    public static String ENCRYPT_NO = "0"; // 应用不加密
    private static final Logger logger = LoggerFactory.getLogger(NeiMengCmccMsgServiceImpl.class);
    private static final String METHOD_URL = "CRM_CS_SRVUPD_SMS_SEND_002";   //接口编码

    private static final String AppId = "502739";   //应用AppId

    private static final String Url = "http://218.202.142.37:11001/oppf";
    private static final String OWNKEY = "1587522";
    private static final String APP_KEY = "b49644385f34023eb9ab929fcbe79bb3"; //私钥
    private static final String public_KEY = "MGcwDQYJKoZIhvcNAQEBBQADVgAwUwJMAJGMC+c+KZSddDjcdnuUoumPofmWjq2Gj3ql/fakh9qeR67WBQ7fFFJYIpMGVglUWXRp7xQlvCx1BcUVvzVxsw3zpTkkUWKD7K0SswIDAQAB"; //公钥




    @Override
    public ResultMsg<?> sendMsg(YunShuSendMessageCodeRequest yunShuSendMessageCodeRequest) {
        String phone = yunShuSendMessageCodeRequest.getPhone();  //手机号
        String productId = yunShuSendMessageCodeRequest.getProductCode();  //商品Id
        String channelCode = yunShuSendMessageCodeRequest.getChannelCode();  //渠道名称
        String ownSign = yunShuSendMessageCodeRequest.getOwnsign();
        String timestampSyan = yunShuSendMessageCodeRequest.getTimestamp();

        String result;


        NeimengCmccMsg neimengCmccMsg = new NeimengCmccMsg();   //准备存放短信记录
        try{
            String method = METHOD_URL;   // 接口编码
            String appId = AppId;   // 应用AppId
            String appkey = APP_KEY;
            String opCode = "SYS71015406";
            String opOrgId = "71012628";
            String channelId = "9137";
            String timestamp =  new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); // 获取当前时间戳的方法

//公共参数,按需填写
            JSONObject reqJson = new JSONObject();
            JSONObject pubJson = new JSONObject();
            JSONObject pageJson = new JSONObject();

            String orderNumber = generateRandomOrderNumber(12);

            pubJson.put("OP_CODE", "SYS71015406");
            pubJson.put("REQ_SERIAL_NO", orderNumber);
            pubJson.put("CHANNEL_ID", "9137");
            pubJson.put("OP_ORG_ID", "71012628");

            pageJson.put("PAGE_SIZE", "2");
            pageJson.put("CURRENT_PAGE", "1");

            reqJson.put("PUB_INFO", pubJson);
            reqJson.put("PAGE_INFO", pageJson);

            // 业务参数,Json格式
            JSONObject busiJson = new JSONObject();
            busiJson.put("ACCESS_NUM", phone);
            busiJson.put("BUSI_CODE", "0001");
            busiJson.put("OFFER_ID", productId);
            busiJson.put("CHANNEL_NAME", "中国移动线上服务商");

            reqJson.put("BUSI_INFO", busiJson);

            JSONObject inputJson = new JSONObject();
            inputJson.put("REQ_PARAM", reqJson);

            String busiParam = inputJson.toString();


            String headerString="http://111.56.125.2:21017/oppf?method="+method+
                    "&appId="+appId+
                    "&OP_CODE="+opCode+
                    "&OP_ORG_ID="+opOrgId+
                    "&CHANNEL_ID="+channelId+
                    "&timestamp="+new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar
                    .getInstance().getTime());

            logger.info("请求地址："+headerString);

            String find = HttpJsonInvokeDemo.encryptMessage(busiParam,"1",APP_KEY,"AES");

            logger.info("加密后的参数："+find);
            log.info("开始保存信息");
            boolean issave = generateSignatureSave(neimengCmccMsg, yunShuSendMessageCodeRequest);

            if (!issave) {
                return ResultMsg.fail(ErrorConstant.paramsErrorCode, ErrorConstant.orderErrorMsg, null);
            }
//            ; charset=UTF-8
            neimengCmccMsg.setRequestText(busiParam);
            log.info("下发短信入参："+busiParam);
            try(HttpResponse responses = HttpUtil.createPost(headerString)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .body(find)
                    .execute()){
                result = responses.body();
            }catch (Exception e) {
                throw new RuntimeException("HTTP 请求失败", e);
            }
            HttpJsonInvokeDemo demo = new HttpJsonInvokeDemo();
            String aes = HttpJsonInvokeDemo.decryptMessage(result, "1", APP_KEY,"AES");

            logger.info("解密后的响应结果："+aes);
//
            neimengCmccMsg.setResultText(aes);

            if (StringUtils.isEmpty(aes)) {
                return ResultMsg.fail(ErrorConstant.paramsErrorCode, ErrorConstant.cmccErrorMsg, null);
            }


            JSONObject resultJsonObject = JSONObject.parseObject(aes);
            neimengCmccMsg.setUpdateDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            this.updateById(neimengCmccMsg);
            // 获取RSP_PARAM对象
            JSONObject rspParam = resultJsonObject.getJSONObject("RSP_PARAM");

            // 获取PUB_INFO对象
            JSONObject pubInfo = rspParam.getJSONObject("PUB_INFO");

            // 获取CODE值
            String code = pubInfo.getString("CODE");
            if ("0".equals(code)) {
                neimengCmccMsg.setState("0");
                neimengCmccMsg.setCheckState("1");
                this.updateById(neimengCmccMsg);
                JSONObject data = new JSONObject();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                // 获取当前时间并格式化
                String dateStr = dateFormat.format(new Date());

                // 生成一个三位随机数
                Random random = new Random();
                int randomNum = random.nextInt(900) + 100; // 生成100到999之间的随机数

                // 拼接日期字符串、随机数和"YP"
                String traceLogIds = dateStr + randomNum + "YP";
                data.put("phone",phone);
                data.put("traceLogId",traceLogIds);
                return ResultMsg.success(ErrorConstant.paramsSuccessCode,"成功",data);
            }

           return ResultMsg.success(ErrorConstant.paramsErrorCode,"失败",resultJsonObject);


        } catch (Exception e) {
            log.info("下发短信异常："+e);
            return ResultMsg.fail(ErrorConstant.paramsErrorCode,"调用接口出错");

        }
    }


    private boolean generateSignatureSave(NeimengCmccMsg neimengCmccMsg,YunShuSendMessageCodeRequest yunShuSendMessageCodeRequest) {
        neimengCmccMsg.setChannelCode("YPJWCS");
        neimengCmccMsg.setPhone(yunShuSendMessageCodeRequest.getPhone());
        neimengCmccMsg.setCreateDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        neimengCmccMsg.setProductCode(yunShuSendMessageCodeRequest.getProductCode());
        neimengCmccMsg.setState("0");
        neimengCmccMsg.setTraceLogId(yunShuSendMessageCodeRequest.getTraceLogId());
        neimengCmccMsg.setProductName(yunShuSendMessageCodeRequest.getProductName());
        neimengCmccMsg.setUa(yunShuSendMessageCodeRequest.getUa());
        neimengCmccMsg.setIp(yunShuSendMessageCodeRequest.getIp());

        return this.save(neimengCmccMsg);
    }


    public static String generateRandomOrderNumber(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            int digit = random.nextInt(10); // 生成0-9之间的随机数字
            sb.append(digit);
        }

        return sb.toString();
    }



}



